<template>
  <el-dialog
    v-model="state.show"
    :title="state.status"
    width="500px"
    modal-class="docBoxes-dailog"
  >
    <el-form
      ref="addFormRef"
      :model="state.addForm"
      label-suffix=":"
      label-width="90px"
      v-if="!state.includeBox"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="当前状态">
            <el-input v-model="state.status" disabled> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="时间">
            <el-date-picker
              v-model="state.stateTime"
              type="datetime"
              placeholder="请选择"
              format="YYYY-MM-DD HH:mm"
              time-format="HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-else>
      <!-- <div style="margin-bottom: 8px">
        <el-button type="primary" @click="add"> 添加 </el-button>
        <el-button type="default" @click="del"> 删除 </el-button>
      </div> -->
      <el-table
        :data="state.addForm.containerStates"
        border
        height="200px"
        size="small"
        ref="table"
        @cell-click="cellClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="40" />
        <el-table-column align="center" label="箱号" show-overflow-tooltip>
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === state.rowIndex &&
                scope.column.no === state.columnIndex
              "
            >
              <el-select
                v-model="scope.row.containerNo"
                placeholder="请选择"
                filterable
                :disabled="scope.row.stateTime"
                @change="
                  containerNoChaneg(
                    scope.row.containerNo,
                    scope.$index,
                    scope.column.no
                  )
                "
              >
                <el-option
                  v-for="item in state.boxOption"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>  v-else-->
            <span>
              {{ scope.row.containerNo ? scope.row.containerNo : '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="箱型" show-overflow-tooltip>
          <template #default="scope">
            <span>
              {{ scope.row.containerSize ? scope.row.containerSize : '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="提箱时间" show-overflow-tooltip>
          <template #default="scope">
            <div
              v-if="
                scope.$index === state.rowIndex &&
                scope.column.no === state.columnIndex
              "
            >
              <el-date-picker
                v-model="scope.row.stateTime"
                type="datetime"
                placeholder="请选择"
                format="YYYY-MM-DD HH:mm"
                time-format="HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
            <span v-else>
              {{ scope.row.stateTime ? scope.row.stateTime : '--' }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div>
        <el-button type="default" @click="state.show = false">取消</el-button>
        <el-button type="primary" @click="modifySubmit"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineComponent, reactive, toRaw } from 'vue'
import AppSearchForm from '@/components/AppSearchForm.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useStore, Store } from 'vuex'
import request from '@/public/request'

const Router = useRouter()
const Route = useRoute()
const store = useStore()

const emit = defineEmits(['getSetpData'])

const state = reactive({
  addForm: {
    bookingId: Route.query.id,
    stateFlag: '',
    containerStates: [
      // {
      //   id: 0,
      //   bookingId: Route.query.id,
      //   containerId: '',
      //   isDeleted: false,
      //   containerNo: '',
      //   stateFlag: '',
      //   stateFlagValue: '',
      //   stateTime: undefined
      // }
    ]
  },
  // 保存当前点击进来的节点
  stepKeys: '',
  tableOption: useTableOption(),
  stateTime: undefined,
  rowIndex: -1,
  columnIndex: -1,
  show: false,
  status: '',
  tableSelect: [],
  // 当前可以选择箱子数据
  boxOption: [],
  // 当前可选中的箱子是否存在没有箱号
  currentBoxNoconatieno: false,
  // 当前的进度位置
  currentKey: '',
  // 不包含箱子的数组
  noBoxsList: ['pick_container', 'enter_port', 'customs_release', 'unloading'],
  // 是否包含箱子
  includeBox: false,
  // 复制的箱型对象
  containerStatesCopy: []
})

//单元格被点击时会触发该事件
async function cellClick(row, column) {
  state.rowIndex = state.addForm.containerStates.findIndex((t) => t == row)
  state.columnIndex = column.no
}

// 对应状态的状态
function checkStatus(stepValue) {
  switch (stepValue) {
    case 'booking_space':
      state.status = '已订舱'
      break
    case 'release_space':
      state.status = '已放舱'
      break
    case 'release_container':
      state.status = '已放箱'
      break
    case 'pick_container':
      state.status = '已提柜'
      break
    case 'enter_port':
      state.status = '已进港'
      break
    case 'customs_release':
      state.status = '已海放'
      break
    case 'wharf_release':
      state.status = '已码放'
      break
    case 'ship_open':
      state.status = '已船开'
      break
    case 'arrive_port':
      state.status = '已抵港'
      break
    case 'unloading':
      state.status = '已卸货'
      break
    case 'pick_cargo':
      state.status = '已提货'
      break
  }
}

//打开弹框
async function open(stepKeys) {
  state.addForm = {
    bookingId: Route.query.id,
    stateFlag: '',
    containerStates: []
  }
  state.stepKeys = stepKeys
  state.rowIndex = -1
  state.columnIndex = -1
  checkStatus(stepKeys.stateFlag)
  if (state.noBoxsList.indexOf(stepKeys.stateFlag) === -1) {
    state.includeBox = false
    state.stateTime = stepKeys.stateTime
    // let res = await request.post('/api/containerstate/query', {
    let res = await request.post('/api/containerstate/querydetail', {
      BookingId: Route.query.id,
      StateFlag: stepKeys.stateFlag
    })
    if (res.content.length) {
      state.addForm.containerStates = res.content
      state.containerStatesCopy = JSON.parse(JSON.stringify(res.content))
    }
  } else {
    state.boxOption = []
    let res = await request.get('/api/secontainer/query', {
      BookingId: Route.query.id
    })
    // res.content.forEach((item) => {
    //   if (item.containerNo) {
    //     item.label = item.containerNo
    //     item.value = item.containerNo
    //     state.boxOption.push(item)
    //   } else {
    //     state.currentBoxNoconatieno = true
    //   }
    // })
    state.addForm.containerStates = res.content
    state.includeBox = true
  }
  state.addForm.stateFlag = stepKeys.stateFlag
  // 原来的逻辑
  // let res = await request.post('/api/containerstate/query', {
  //   BookingId: Route.query.id,
  //   StateFlag: stepKeys.stateFlag
  // })
  // if (res.content.length) {
  //   state.addForm.containerStates = res.content
  //   state.containerStatesCopy = JSON.parse(JSON.stringify(res.content))
  // }
  state.show = true
}

// 添加
function add() {
  if (state.boxOption.length) {
    if (state.boxOption.length == state.addForm.containerStates.length) {
      if (state.currentBoxNoconatieno) {
        ElMessage.warning('存在箱子未填写箱号')
      } else {
        ElMessage.warning('已添加完所有的箱子')
      }
      return
    }
  } else {
    if (state.currentBoxNoconatieno) {
      ElMessage.warning('存在箱子未填写箱号')
    } else {
      ElMessage.warning('当前数据请先载入箱子')
    }
    return
  }
  state.addForm.containerStates.push({
    id: 0,
    bookingId: Route.query.id,
    containerId: '',
    isDeleted: false,
    containerNo: '',
    stateOrder: state.stepKeys.stateOrder,
    stateFlag: '',
    stateFlagValue: '',
    stateTime: undefined
  })
  state.containerStatesCopy = JSON.parse(
    JSON.stringify(state.addForm.containerStates)
  )
}
/**
 * 选择后的数据
 */
function handleSelectionChange(val) {
  let arr = []
  for (let item of val) {
    let ret = toRaw(item)
    if (ret !== undefined) {
      arr.push(ret)
    }
  }
  state.tableSelect = arr
}

// 删除
function del() {
  for (let i = state.tableSelect.length - 1; i >= 0; i--) {
    let selectItem = state.tableSelect[i]
    let deleteIndex = state.addForm.containerStates.findIndex(
      (t) => t == selectItem
    )
    if (deleteIndex > -1) {
      state.addForm.containerStates.splice(deleteIndex, 1)
    }
  }
  state.containerStatesCopy = JSON.parse(
    JSON.stringify(state.addForm.containerStates)
  )
}

// 重新选择箱号,当箱号重复时，使用备份数据覆盖
function containerNoChaneg(val, index) {
  let fillContainerId = true
  for (const iterator of state.containerStatesCopy) {
    if (val == iterator.containerNo) {
      fillContainerId = false
      state.addForm.containerStates = JSON.parse(
        JSON.stringify(state.containerStatesCopy)
      )
      break
    }
  }
  if (fillContainerId) {
    for (const iterator of state.boxOption) {
      if (iterator.containerNo == val) {
        state.addForm.containerStates[index].containerId = iterator.id
        break
      }
    }
  }
}

// 保存
async function modifySubmit() {
  let addForm = JSON.parse(JSON.stringify(state.addForm))
  if (state.noBoxsList.indexOf(state.addForm.stateFlag) === -1) {
    addForm.containerStates = [
      {
        id: 0,
        bookingId: Route.query.id,
        containerId: '',
        isDeleted: false,
        stateOrder: state.stepKeys.stateOrder,
        containerNo: '',
        stateFlag: state.addForm.stateFlag,
        stateFlagValue: state.addForm.stateFlag + '_time',
        stateTime: state.stateTime
      }
    ]
  } else {
    // 存在箱子的情况下新增
    addForm.containerStates = []
    for (const iterator of state.addForm.containerStates) {
      // if (iterator.containerNo) {
      iterator.stateFlag = state.addForm.stateFlag
      iterator.stateFlagValue = state.addForm.stateFlag + '_time'
      addForm.containerStates.push(iterator)
      // }
    }
  }
  let res = await request.post('/api/containerstate/save', addForm)
  if (res.status) {
    state.show = false
    ElMessage.success('成功')
    emit('getSetpData')
  } else {
    ElMessage.warning(res.message)
  }
}

defineExpose({
  open
})
</script>

<style lang="scss">
.docBoxes-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
    padding: 7px 16px 7px 16px;
  }

  .el-dialog {
    min-width: 630px;
    padding: 0px;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
    text-align: center;
  }
}
</style>
<style lang="scss" scoped>
.from-container {
  border: 1px solid #e8e8e8;
  padding: 6px;
  margin-bottom: 8px;
}

:deep(.el-form-item--small .el-form-item__label) {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.el-form--inline .el-form-item) {
  display: flex;
  margin-right: 0;
}

:deep(.el-form-item--small.el-form-item) {
  margin-bottom: 8px;
}

:deep(.el-form--inline .el-form-item) {
  display: flex;
}
</style>
